#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <unistd.h>

#include <stdio.h>
#include "cmsis_os2.h"
#include "ohos_run.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "driver/i2c.h"


#include "max30102.h"

#define I2C0_I2C_IDX    0




uint8_t max30102_Bus_Write(uint8_t Register_Address, uint8_t Word_Data)
{
    int i;
    i2c_cmd_handle_t cmd_handle = i2c_cmd_link_create();
 
    i2c_master_start(cmd_handle);
    i2c_master_write_byte(cmd_handle, I2C_WRITE_ADDR, true);

    i2c_master_write_byte(cmd_handle, Register_Address, true);
    i2c_master_write_byte(cmd_handle, Word_Data, true);


    i2c_master_stop(cmd_handle);
    esp_err_t error = i2c_master_cmd_begin(I2C_NUM_0,cmd_handle,100);
 
    i2c_cmd_link_delete(cmd_handle);

    return error;
}

void max30102_reset(void)
{
	max30102_Bus_Write(REG_MODE_CONFIG,0x40);
	max30102_Bus_Write(REG_MODE_CONFIG,0x40);
}



uint8_t max30102_FIFO_ReadBytes(uint8_t Register_Address,uint8_t* Data, uint32_t len)
{
    esp_err_t err = ESP_OK;
    i2c_cmd_handle_t handle = i2c_cmd_link_create();
    assert (handle != NULL);   
    err = i2c_master_start(handle);
    if (err != ESP_OK) {
        goto end;
    }
    err = i2c_master_write_byte(handle, I2C_WRITE_ADDR, true);
    if (err != ESP_OK) {
        goto end;
    }
    err = i2c_master_write_byte(handle, Register_Address, true);
    if (err != ESP_OK) {
        goto end;
    }
    err = i2c_master_start(handle);
    if (err != ESP_OK) {
        goto end;
    }
    err = i2c_master_write_byte(handle, I2C_READ_ADDR, true);
    if (err != ESP_OK) {
        goto end;
    }
    err = i2c_master_read(handle, Data, len, I2C_MASTER_LAST_NACK);
    if (err != ESP_OK) {
        goto end;
    }
    i2c_master_stop(handle);
    err = i2c_master_cmd_begin(I2C_NUM_0, handle, 100);
end:
    i2c_cmd_link_delete(handle);
    return err;
}


void max30102_init(void)
{
    max30102_reset();

	
	max30102_Bus_Write(REG_INTR_ENABLE_1,0xc0);	// INTR setting
	max30102_Bus_Write(REG_INTR_ENABLE_2,0x00);
	max30102_Bus_Write(REG_FIFO_WR_PTR,0x00);  	//FIFO_WR_PTR[4:0]
	max30102_Bus_Write(REG_OVF_COUNTER,0x00);  	//OVF_COUNTER[4:0]
	max30102_Bus_Write(REG_FIFO_RD_PTR,0x00);  	//FIFO_RD_PTR[4:0]
	max30102_Bus_Write(REG_FIFO_CONFIG,0x0f);  	//sample avg = 1, fifo rollover=false, fifo almost full = 17
	max30102_Bus_Write(REG_MODE_CONFIG,0x03);  	//0x02 for Red only, 0x03 for SpO2 mode 0x07 multimode LED
	max30102_Bus_Write(REG_SPO2_CONFIG,0x27);  	// SPO2_ADC range = 4096nA, SPO2 sample rate (100 Hz), LED pulseWidth (400uS)  
	max30102_Bus_Write(REG_LED1_PA,0x24);   	//Choose value for ~ 7mA for LED1
	max30102_Bus_Write(REG_LED2_PA,0x24);   	// Choose value for ~ 7mA for LED2
	max30102_Bus_Write(REG_PILOT_PA,0x7f);   	// Choose value for ~ 25mA for Pilot LED

}